package com.yzyz.management.web;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.yzyz.bean.scenic.PictureBean;
import com.yzyz.service.PictureService;
import com.yzyz.utils.CommonHandle;
import com.yzyz.utils.Global;
import com.yzyz.utils.ValidateUtils;
import com.yzyz.utils.error.Error;
import com.yzyz.utils.error.ErrorBean;
import com.yzyz.utils.json.management.JSONPictureM;

/**
 * 图片上传
 * @author David Sun
 * @Date   2010-3-21
 *
 */
public class PictureController extends MultiActionController {
	Log logger = LogFactory.getLog(PictureController.class);
	private PictureService pictureService;
	public void setPictureService(PictureService pictureService) {
		this.pictureService = pictureService;
	}

	/**
	 * To handle picture uploading
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ModelAndView upload(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		if(!(request instanceof MultipartHttpServletRequest)) {
			ModelAndView mv = new ModelAndView("/Admin/Error/error.jsp");
			mv.addObject("errorMsg","您上传的图片为空");
			return mv;
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
		MultipartFile file = multipartRequest.getFile("image");
		String strOwnerId = request.getParameter("scenicId");
		if(ValidateUtils.isNull(strOwnerId)) {
			ModelAndView mv = new ModelAndView("/Admin/Error/error.jsp");
			mv.addObject("errorMsg","您上传的图片为空");
			return mv;
		}
		if(this.pictureService.checkCount(Integer.valueOf(strOwnerId)) != Error.SUCCESS) {
			ModelAndView mv = new ModelAndView("/Error/error.jsp");
			mv.addObject(Global.ERRORMSG, Error.errorMsg[Error.PICUTURE_OVER_COUNT]);
			return mv;
		}
		InputStream in = file.getInputStream();
		long size = file.getSize();
		byte [] image = new byte[(int)size];
		int left = image.length;
		int read = 0;
		while(read != -1 && left > 0) {
			read = in.read(image, image.length - left, left);
			left = image.length - read;
			System.out.println("read:" + ((float)(image.length-left)/(float)image.length));
		}
		BufferedImage bi = this.pictureService.bytes2Image(image);
		image = this.pictureService.resize(bi, 600, 450, "jpeg");
		PictureBean p = new PictureBean();
		p.setAvailable(false);
		p.setContents(image);
		p.setDate(new Date());
		p.setDescription(request.getParameter("description"));
		p.setLevel(0);
		p.setName(request.getParameter("name")==null?"未命名":request.getParameter("name"));
		p.setOwnerId(Integer.valueOf(strOwnerId));
		this.pictureService.add(p);
		return new ModelAndView("/Admin/Scenic/Picture/picture.jsp?scenicId" + strOwnerId);
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	public void viewImages(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String strOwnerId = request.getParameter("scenicId");
		if(ValidateUtils.isNull(strOwnerId)) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			logger.warn(CommonHandle.now() + " The sceniceId is null. Refused viewing images");
			return;
		}
		List<PictureBean> pictures = this.pictureService.getPicturesWithoutContents(Integer.valueOf(strOwnerId));
		List<JSONPictureM> list = new ArrayList<JSONPictureM>();
		String url = CommonHandle.getUrl(request);
		if(pictures != null) {
			for(PictureBean picture: pictures) {
				JSONPictureM p = new JSONPictureM(picture, url);
				list.add(p);
			}
		}
		JSONArray js = JSONArray.fromObject(list, JSONPictureM.getConfig());
		StringBuilder sb = new StringBuilder();
		sb.append("{\"images\":").append(js.toString()).append("}");
		this.writeToClient(response, sb.toString());
	}
	
	public void getImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String imageId = request.getParameter("pictureId");
		if(ValidateUtils.isNull(imageId)){
			return;
		}
		String scenicId = request.getParameter("scenicId");
		if(ValidateUtils.isNull(scenicId)) {
			return;
		}
		PictureBean p = this.pictureService.getPicture(Integer.valueOf(imageId));
		if(p == null) {
			return;
		}
		
		byte[] image = this.pictureService.resize(this.pictureService.bytes2Image(p.getContents()), 80, 60, "jpg");
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "attachment; filename=" + p.getName());//设置图片的名字
		response.setContentLength(image.length);
		OutputStream out = response.getOutputStream();
		out.write(image);
		out.flush();
		out.close();
	}
	public void getImageForEdit(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String imageId = request.getParameter("pictureId");
		if(ValidateUtils.isNull(imageId)){
			return;
		}
		String scenicId = request.getParameter("scenicId");
		if(ValidateUtils.isNull(scenicId)) {
			return;
		}
		PictureBean p = this.pictureService.getPicture(Integer.valueOf(imageId));
		if(p == null) {
			return;
		}
		
		byte[] image = this.pictureService.resize(this.pictureService.bytes2Image(p.getContents()), 300, 215, "jpg");
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "attachment; filename=" + p.getName());//设置图片的名字
		response.setContentLength(image.length);
		OutputStream out = response.getOutputStream();
		out.write(image);
		out.flush();
		out.close();
	}
	public void delete(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String strPictureId = request.getParameter("pictureId");
		if(ValidateUtils.isNull(strPictureId)) {
			ErrorBean error = new ErrorBean();
			error.setCode(Error.OP_FAILED);
			error.setMessage("删除失败");
			this.writeToClient(response, error.toJson());
			return;
		}
		this.pictureService.delete(Integer.valueOf(strPictureId));
		ErrorBean error = new ErrorBean();
		error.setCode(Error.SUCCESS);
		error.setMessage("删除成功");
		this.writeToClient(response, error.toJson());
	}
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void update(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String name = request.getParameter("name");
		String description = request.getParameter("description");
		String strPictureId = request.getParameter("pictureId");
		if(ValidateUtils.isNull(strPictureId)){
			ErrorBean error = new ErrorBean();
			error.setCode(Error.OP_FAILED);
			error.setMessage(Error.errorMsg[error.getCode()]);
			this.writeToClient(response, error.toJson());
			return;
		}
		if(description.length() > 200) {
			ErrorBean error = new ErrorBean();
			error.setCode(Error.PICTUE_DES_LESS_THAN_100);
			error.setMessage(Error.errorMsg[error.getCode()]);
			this.writeToClient(response, error.toJson());
			return;
		}
		PictureBean p = new PictureBean();
		p.setDescription(description);
		p.setName(name);
		p.setId(Integer.valueOf(strPictureId));
		this.pictureService.update(p);
		ErrorBean error = new ErrorBean();
		error.setCode(Error.SUCCESS);
		this.writeToClient(response, error.toJson());
		
	}
	private void writeToClient(HttpServletResponse response, String contents) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Programa", "no-cache");
		response.setDateHeader("Expires", -1L);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write(contents);
		response.flushBuffer();
		response.getWriter().close();
	}
}
